package common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Manage communication with Sqlite
 * @author Boshi Li
 *
 */
public class SqliteManager {

	public static ResultSet getResult( String sql ) throws Exception{
		Class.forName("org.sqlite.JDBC");
        String database = "jdbc:sqlite:data/laptops.db";
        Connection connection = DriverManager.getConnection( database ,"",""); 
        Statement statement = connection.createStatement();
        boolean found = statement.execute(sql);
        if( found ){
        	ResultSet set = statement.getResultSet();
        	return set;
        }else{
        	throw new Exception("error: no result");
        }
	}
	
	public static void displayResults(ResultSet rs) throws SQLException {
        ResultSetMetaData metaData = rs.getMetaData();
        int columns=metaData.getColumnCount();
        String text="";

        while(rs.next()){
            for(int i=1;i<=columns;++i) {
                text+=""+metaData.getColumnName(i)+":\t";
                text+=rs.getString(i);
                //text+="</"+metaData.getColumnName(i)+">";
                text+="\n";
            }
            text+="\n";
        }

        System.out.println(text);

    }
}
